<template>
  <transition name="toast">
    <div v-if="visible" class="toast">
      <div class="toast-message">{{ message }}</div>
      <div class="toast-progress">
        <div class="progress-bar" :style="progressStyle"></div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const visible = ref(false)
const message = ref('')
const progress = ref(100)
let timer: NodeJS.Timeout | null = null

const progressStyle = computed(() => ({
  width: `${progress.value}%`,
}))

const show = (msg: string, duration = 5000) => {
  if (timer) clearTimeout(timer)
  message.value = msg
  progress.value = 100
  visible.value = true

  const startTime = Date.now()
  const updateProgress = () => {
    const elapsed = Date.now() - startTime
    progress.value = Math.max(0, 100 * (1 - elapsed / duration))
    if (progress.value > 0) {
      requestAnimationFrame(updateProgress)
    }
  }
  requestAnimationFrame(updateProgress)

  timer = setTimeout(() => {
    visible.value = false
  }, duration)
}

defineExpose({ show })
</script>

<style scoped>
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-width: 300px;
}

.toast-enter-active,
.toast-leave-active {
  transition: all 0.3s ease;
}

.toast-enter-from,
.toast-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

.toast-progress {
  width: 100%;
  height: 2px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 1px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #409EFF;
  transition: width 0.1s linear;
}
</style>